package com.example.onlinetaxi.ui.activity.Driver.MainPage;

import android.app.Activity;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.example.onlinetaxi.BaiDuMap.BaiDuMapManager;
import com.example.onlinetaxi.BaiDuMap.MyGeoCoder;
import com.example.onlinetaxi.LocalStroage.CurrentFragment;
import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.Thread.DriverReceiveOrderThread;
import com.example.onlinetaxi.callback.DriverCallBack.ILocationChange;
import com.example.onlinetaxi.callback.IExchangeFragments;
import com.example.onlinetaxi.callback.OrderCallBack.BackToGetOrderCallBack;
import com.example.onlinetaxi.ui.activity.Driver.MainPage.WaitingOrderFragment.CancelGetOrderFragment;
import com.example.onlinetaxi.ui.activity.Driver.MainPage.WaitingOrderFragment.GetOrderFragment;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;

import java.util.HashMap;
import java.util.Map;

public class DriverMapFragment extends Fragment implements View.OnClickListener {

    // 根控件
    private View rootView;
    // 控件
    private MapView mMapView;  // 地图
    private ImageView mMyLocation;  // 返回当前位置按钮
    private TextView mapCityTv;  // 当前城市
    private TextView addressTv;  // 当前场所
    // activity对象
    private FragmentActivity fragmentActivity;
    // 获取fragment
    private GetOrderFragment getOrderFragment = new GetOrderFragment();
    private CancelGetOrderFragment cancelGetOrderFragment = new CancelGetOrderFragment();
    // 传入参数
    private Map<String, String> map = new HashMap<>();
    // fragment切换
    private IExchangeFragments iExchangeFragments;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_driver_map, container, false);

        fragmentActivity = getActivity();

        initView();

        initEvent();

        // 关闭加载框
        DriverMainActivity.closeProgressDialog();

        return rootView;
    }

    private void initEvent() {
        // 获取司机当前位置信息
        BaiDuMapManager.baiDuMapManager.setLocationChange(new ILocationChange() {
            @Override
            public void changeDriverUi(String city, String address, LatLng latLng) {
                // 更新UI
                mapCityTv.setText(city);
                addressTv.setText(address);

                // 保存到后端
                saveDriverInfo(city, address, latLng);
            }
        });
        // 设置fragment的跳转
        getOrderFragment.setiExchangeFragments(new IExchangeFragments() {
            @Override
            public void exchangeFragment() {
                replaceFragment(cancelGetOrderFragment);
            }
        });
        cancelGetOrderFragment.setiExchangeFragments(new IExchangeFragments() {
            @Override
            public void exchangeFragment() {
                replaceFragment(getOrderFragment);
            }
        });
        getOrderFragment.setBackToGetOrderCallBack(new BackToGetOrderCallBack() {
            @Override
            public void backToGetOrder() {
                // 取消出车线程
                DriverReceiveOrderThread.finished = true;
                // 确保线程终止
                DriverReceiveOrderThread.thread = null;
                DriverReceiveOrderThread.bestOrderCallBack = null;

                // 改变司机状态
                cancelGetOrderFragment.sendCancelGetOrderRequest();

                // 回到最初的fragment
                // 切换主页面fragment
                iExchangeFragments.exchangeFragment();

                replaceFragment(getOrderFragment);
            }
        });
    }

    private void initView() {
        // 初始化控件
        mMapView = rootView.findViewById(R.id.bmapView);

        // 城市提示框
        mapCityTv = rootView.findViewById(R.id.driver_map_city_tv);

        // 司机当前位置
        addressTv = rootView.findViewById(R.id.driver_map_location);

        // 初始化地图管理者
        BaiDuMapManager.baiDuMapManager.setActivity(getActivity());  // 先传递依附主体
        // 开启定位和反地理编码
        BaiDuMapManager.baiDuMapManager.isLocate(true);
        BaiDuMapManager.baiDuMapManager.isOpenGeoReverse(false);
        BaiDuMapManager.baiDuMapManager.setMapView(mMapView);
        // 初始化“回到当前位置”按钮
        mMyLocation = rootView.findViewById(R.id.driver_my_location);
        // 添加点击事件
        mMyLocation.setOnClickListener(this);

        // 替换fragment
        if (CurrentFragment.currentFragment == null) {
            replaceFragment(getOrderFragment);
        } else {
            // 切换到上一个退出的current
            replaceFragment(CurrentFragment.currentFragment);
        }
    }

    // 将用户定位到的城市传入后端
    private void saveDriverInfo(String city, String address, LatLng latLng) {
        if (LocalStorage.longitude == null
                || !LocalStorage.longitude.equals(String.valueOf(latLng.longitude))
                || !LocalStorage.latitude.equals(String.valueOf(latLng.latitude))) {
            // 第一次定位 或 经纬度有一个改变（发生移动）
            map.put("phone", LocalStorage.phone);
            map.put("city", city);
            map.put("longitude", String.valueOf(latLng.longitude));
            map.put("latitude", String.valueOf(latLng.latitude));
            map.put("address", address);
            // 保存
            LocalStorage.latitude = String.valueOf(latLng.latitude);
            LocalStorage.longitude = String.valueOf(latLng.longitude);

            OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "driver", "saveLocation");
        }
    }

    // 进行碎片之间的切换
    private void replaceFragment(Fragment fragment) {
        // 设置当前fragment
        CurrentFragment.currentFragment = fragment;

        // 获取碎片管理类
        FragmentManager fragmentManager = fragmentActivity.getSupportFragmentManager();
        // 开启碎片事物
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // 创建事务
        fragmentTransaction.replace(R.id.driver_map_fragment, fragment);
        // 提交事务
        fragmentTransaction.commit();
    }

    public void setFirstLocation() {
        // 确保每次加载时都进行定位
        BaiDuMapManager.baiDuMapManager.isFirstLocate = true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.driver_my_location:
                // 回归到当前位置
                BaiDuMapManager.baiDuMapManager.backToLocation();
                break;
        }
    }

    // 解决界面二次打开，内嵌fragment空白问题
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (getOrderFragment != null) {

            FragmentManager f = getFragmentManager();
            if (f != null) {
                final FragmentTransaction ft = f.beginTransaction();
                if (ft != null) {
                    ft.remove(getOrderFragment).commit();
                }
            }
        }
        if (cancelGetOrderFragment != null) {

            FragmentManager f = getFragmentManager();
            if (f != null) {
                final FragmentTransaction ft = f.beginTransaction();
                if (ft != null) {
                    ft.remove(cancelGetOrderFragment).commit();
                }
            }
        }
    }

    public void setiExchangeFragments(IExchangeFragments iExchangeFragments) {
        this.iExchangeFragments = iExchangeFragments;
    }

    @Override
    public void onResume() {
        super.onResume();

        if (BaiDuMapManager.baiDuMapManager.mMapView == null) {
            BaiDuMapManager.baiDuMapManager.setMapView(mMapView);
        }

        // 在activity执行onResume时必须调用mMapView.onResume()
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时必须调用mMapView.onPause()
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        BaiDuMapManager.baiDuMapManager.destroy();

        MyGeoCoder.myGeoCoder.destroy();
    }
}